package com.xk.sport.backend.web.controller;

import com.google.common.base.Strings;
import com.xk.sport.backend.common.annotation.Login;
import com.xk.sport.backend.common.constant.ResultStatus;
import com.xk.sport.backend.common.entity.Result;
import com.xk.sport.backend.common.entity.TaskQuery;
import com.xk.sport.backend.common.util.XlsUtil;
import com.xk.sport.backend.dao.model.Community;
import com.xk.sport.backend.dao.model.Lesson;
import com.xk.sport.backend.dao.model.Task;
import com.xk.sport.backend.dao.model.Teacher;
import com.xk.sport.backend.dao.repository.CommunityDao;
import com.xk.sport.backend.dao.repository.LessonDao;
import com.xk.sport.backend.service.TaskService;
import org.apache.poi.ss.usermodel.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Login
@Controller
@RequestMapping(value = "/task")
public class TaskController {
    @Autowired
    private TaskService taskService;
    @Autowired
    private LessonDao lessonDao;
    @Autowired
    private CommunityDao communityDao;

    /**
     * 查询
     */
    @RequestMapping("/findAllByQueryAndPage")
    @ResponseBody
    public Result findAllByQueryAndPage(TaskQuery query) {
        Page<Task> page = taskService.findAllByQuery(query);
        return new Result(ResultStatus.success.getStatus(), "", page);
    }

    /**
     * 查询
     */
    @RequestMapping("/findOne")
    @ResponseBody
    public Result findOne(long id) {
        Task task = taskService.findOne(id);
        return new Result(ResultStatus.success.getStatus(), "", task);
    }

    /**
     * 添加
     */
    @RequestMapping("/add")
    @ResponseBody
    public Result add(Task task) {
        Task newTask = taskService.add(task);
        if (newTask != null) {
            return new Result(ResultStatus.success.getStatus(), "", newTask);
        } else {
            return new Result(ResultStatus.normal_error.getStatus(), "添加失败");
        }
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @ResponseBody
    public Result update(Task task) {
        Task newTask = taskService.update(task);
        if (newTask != null) {
            return new Result(ResultStatus.success.getStatus(), "", newTask);
        } else {
            return new Result(ResultStatus.normal_error.getStatus(), "修改失败");
        }
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @ResponseBody
    public Result delete(long id) {
        if (taskService.delete(id)) {
            return new Result(ResultStatus.success.getStatus(), "");
        } else {
            return new Result(ResultStatus.normal_error.getStatus(), "删除失败");
        }
    }

    /**
     * 上传
     */
    @RequestMapping("/upload")
    @ResponseBody
    public Result upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return new Result(ResultStatus.normal_error.getStatus(), "文件为空");
        }
        String originalFileName = file.getOriginalFilename();
        if (Strings.isNullOrEmpty(originalFileName)) {
            return new Result(ResultStatus.normal_error.getStatus(), "文件名为空");
        }
        final List<Task> tasks = new ArrayList<>();
        int startrow = 0;
        int startcol = 0;
        XlsUtil.XlsErrorResult xlsErrorResult = XlsUtil.parseXls(file, startrow, startcol, (cellValue, i, j) -> {
            Task task = null;
            if (j == startcol) {
                task = new Task();
                tasks.add(task);
            } else {
                task = tasks.get(i - startrow);
            }
            cellValue = cellValue.trim();
            switch (j - startcol) {
                case 0:// 课程名对应lessonId
                    Long[] lessonIds = lessonDao.findIdsByName(cellValue);
                    if (lessonIds == null || lessonIds.length <= 0) {
                        return new XlsUtil.XlsErrorResult(i, j, "课程名不存在");
                    }
                    long lessonId = lessonIds[0];
                    task.setLessonId(lessonId);
                    break;
                case 1:// 街道对应communityId
                    Long[] communityIds = communityDao.findIdsByName(cellValue);
                    if (communityIds == null || communityIds.length <= 0) {
                        return new XlsUtil.XlsErrorResult(i, j, "街道名不存在");
                    }
                    long communityId = communityIds[0];
                    task.setCommunityId(communityId);
                    break;
                case 2:// 开始时间对应startTime
                    try {
                        task.setStartTime(Long.parseLong(cellValue));
                    } catch (Exception e) {
                        return new XlsUtil.XlsErrorResult(i, j, "时间格式不正确");
                    }
                    break;
                case 3:// 结束时间对应endTime
                    try {
                        task.setEndTime(Long.parseLong(cellValue));
                    } catch (Exception e) {
                        return new XlsUtil.XlsErrorResult(i, j, "时间格式不正确");
                    }
                    break;
                case 4:// 描述对应content
                    task.setContent(cellValue);
                    break;
            }
            return new XlsUtil.XlsErrorResult();
        });

        if (xlsErrorResult.hasError()) {
            return new Result(ResultStatus.normal_error.getStatus(), xlsErrorResult.toString());
        }

        for (Task task : tasks) {
            taskService.add(task);
        }
        return new Result(ResultStatus.success.getStatus(), "");
    }

    /**
     * 下载
     *
     * @param day    最近几天的数据
     * @param status 需要什么状态
     * @return
     */
    @RequestMapping(value = "/download")
    public ResponseEntity<byte[]> download(int day, int status) {
        String fileName = "task_result_for_" + day + ".xlsx";
        long endTime = System.currentTimeMillis();
        long startTime = endTime - DateUtil.DAY_MILLISECONDS * day;
        List<Task> tasks = taskService.findByCondition(startTime, endTime, status);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<List<String>> data = new ArrayList<>();
        List<String> th = new ArrayList<>();
        th.add("课程名称");
        th.add("上课时间");
        th.add("结束时间");
        th.add("上课地点");
        th.add("上课地点联系人");
        th.add("上课地点联系方式");
        th.add("配送老师");
        th.add("配送老师联系方式");
        data.add(th);
        if (tasks != null) {
            for (Task task : tasks) {
                Lesson lesson = task.getLesson();
                Teacher teacher = task.getTeacher();
                Community community = task.getCommunity();
                String teacherName = "";
                String teacherContact = "";
                if (lesson == null || community == null) {
                    continue;
                }
                if (teacher != null) {
                    teacherName = teacher.getName();
                    teacherContact = teacher.getContact();
                }
                List<String> line = new ArrayList<>();
                line.add(lesson.getName());
                line.add(simpleDateFormat.format(new Date(task.getStartTime())));
                line.add(simpleDateFormat.format(new Date(task.getEndTime())));
                line.add(community.getName() + " " + community.getContent());
                line.add(community.getContactBody());
                line.add(community.getContactPhone());
                line.add(teacherName);
                line.add(teacherContact);
                data.add(line);
            }
        }

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", fileName);
        return new ResponseEntity<byte[]>(XlsUtil.createXls(data), headers, HttpStatus.CREATED);
    }
}
